<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\FeedsModel;
use yii\base\Exception;

class FeedsForm extends Model
{
    public $content;
    
    public $_lastError = "";
    
    public function rules()
    {
        return [
            ['content', 'required'],
            ['content', 'string', 'max' => 255],
        ];
    }
    
    public function attributeLabels()
    {
        return [
            'id' => '编号',
            'content' => '评论内容',
        ];
    }
    
    /**
     * 保存留言的方法
     * @throws Exception
     * @return boolean
     */
    public function create()
    {
        try {
            $model = new FeedsModel();
            $model->user_id = Yii::$app->user->identity->id;
            $model->content = $this->content;
            $model->created_at = time();
            
            if (!$model->save())
                throw new Exception("留言失败！");
            return true;
        } catch (Exception $e) {
            $this->_lastError = $e->getMessage();
            return false;
        }
    }
    /**
     * 获取留言的数据
     */
    public function getList()
    {
        $model = new FeedsModel();
        $result = $model->find()
            ->limit(10)
            ->with('user')
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();
        
        return $result?:[];
    }
}